package map.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import map.tools.uimodel.WidgetsModelsSerializer;

import org.eclipse.emf.ecore.util.EcoreUtil;

import uimigration.Interactions.Behaviour;
import uimigration.WidgetsModel.APIModel;
import uimigration.WidgetsModel.Widget;

public class WidgetManager {
	private boolean DEBUG=false;
	private APIModel apiModel;
	private APIModel apiSource;
	private WidgetEquivalence _myEqui= null;
	public WidgetManager (String apiFile, String apiSourceFile)
	{
		apiModel= new WidgetsModelsSerializer().load(new File(apiFile));
		apiSource = new WidgetsModelsSerializer().load(new File(apiSourceFile));
		_myEqui= new WidgetEquivalence();
		
	}

	//Found all widgets that have equivalent behaviors or more
	public List<Widget> findEquivalentWidgets(Widget widget){
		boolean isContains=_myEqui.isContainsWidget(widget, apiSource);
		List<Widget> foundW=new ArrayList<Widget>();
		for(int i=0; i<apiModel.getContainsLength();i++){
			Widget wi=(Widget)EcoreUtil.copy(apiModel.getContains(i));
			if(_myEqui.rootEquivanence(widget, wi))
				foundW.add(wi);
			else if(isContains && wi.getContainsWidgetLength()>0){
				if(_myEqui.containsStructureEquivalence(widget, wi.getContainsWidget().get(0)) && _myEqui.contentEquivalent(widget, wi))
					if(_myEqui.behaviorsEquivalence(widget,  wi.getContainsWidget().get(0)))
						foundW.add( wi.getContainsWidget().get(0));
			}
			else if(!isContains&& _myEqui.containsStructureEquivalence(widget, wi) )
			{	
				if(  _myEqui.behaviorsEquivalence(widget,  wi)&& _myEqui.contentEquivalent(widget, wi))
					
					foundW.add( wi);						
			}
		}
		if(foundW!=null && DEBUG)
			System.out.println("Test findEquivalentWidgets: "+testFind(widget, foundW));
		return foundW;	
	}

	
	public List<Widget> findEquivalenImplementedtWidgets(boolean root,boolean container, List<Integer> card, List<Behaviour> listB, Widget widget){
		List<Widget> foundW=new ArrayList<Widget>();
		for(int i=0; i<apiModel.getContainsLength();i++){
			Widget wi=(Widget)EcoreUtil.copy(apiModel.getContains(i));
			if(wi.isIsRoot()&&root)
				foundW.add(wi);
			else if(wi.isIsContainer()==container &&  _myEqui.contentEquivalent(widget, wi)){
				if(_myEqui.equivalentBehavior(listB, wi.getBehavior()))
					foundW.add( wi);						
			}
		}
		return foundW;	
	}

	public String testFind(Widget looking,List<Widget> found)
	{
		String ret="";
		ret+="Looking for :"+looking.getName()+" isContainer="+looking.isIsContainer()+"\n";
		for(Behaviour b:looking.getBehavior())
			ret+="-"+b.getClass().getSimpleName()+"\n";
		ret+="Found :\n";
		for(Widget w:found){
			ret+="+"+w.getName()+" "+w.getId()+" isContainer="+w.isIsContainer()+"\n";
			for(Behaviour bi:w.getBehavior())
				ret+=bi.getClass().getSimpleName()+"\n";
		}
		
		return ret;
	}
	

}
